import request from '@/plugin/axios'
const _getPostData = function (dataObj) {
  let postData = []
  for (var k in dataObj) {
    postData.push(k + '=' + dataObj[k])
  }
  return postData.join('&')
}
const util = {
  // 对日期进行格式化操作
  formatDate (d, format) {
    if (!(d instanceof Date)) {
      return ''
    }
    var o = {
      'M+': d.getMonth() + 1, // month
      'd+': d.getDate(), // day
      'h+': d.getHours(), // hour
      'm+': d.getMinutes(), // minute
      's+': d.getSeconds(), // second
      'q+': Math.floor((d.getMonth() + 3) / 3), // quarter
      'S': d.getMilliseconds() // millisecond
    }
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1,
        (d.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(format)) {
        format = format.replace(RegExp.$1,
          RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
      }
    }
    return format
  },
  fetchData (url) {
    this.loading = true
    return new Promise((resolve, reject) => {
      request.get(url).then(response => {
        console.log('获取到的数据为: ', response)
        this.listData = response.lists
        if (this.pageData) {
          this.pageData.total = response.total
        }
        this.loading = false
        resolve.call(this, response)
      }).catch(err => {
        reject.call(this, err)
      })
    })
  },
  // 使用POST添加数据
  addData (baseUrl, data) {
    let _self = this
    let postDataStr = _getPostData(data)
    this.loading = true
    if (typeof this.formOptions === 'object') {
      this.formOptions.saveLoading = true
    }
    return new Promise((resolve, reject) => {
      console.log('此时新增的数据为：', postDataStr)
      // ?name=yangfan&level=2
      request.post(baseUrl + '?' + postDataStr).then(response => {
        _self.loading = false
        _self.$message({
          message: '保存成功',
          type: 'success'
        })
        if (typeof this.formOptions === 'object') {
          this.formOptions.saveLoading = false
        }
        resolve.call(_self, response)
      }).catch(err => {
        this.loading = false
        if (typeof this.formOptions === 'object') {
          this.formOptions.saveLoading = false
        }
        _self.$message({
          message: '保存失败! ' + err,
          type: 'error'
        })
        reject.call(_self, err)
      })
    })
  },
  // 使用put对数据进行编辑，编辑的数据放置到url上
  editData (baseUrl, data) {
    let _self = this
    delete data.id
    let postDataStr = _getPostData(data)
    let url = baseUrl + '?' + postDataStr
    this.loading = true
    if (typeof this.formOptions === 'object') {
      this.formOptions.saveLoading = true
    }
    return new Promise((resolve, reject) => {
      request.put(url).then(response => {
        _self.$message({
          message: '保存成功',
          type: 'success'
        })
        if (typeof this.formOptions === 'object') {
          this.formOptions.saveLoading = false
        }
        resolve.call(_self, response)
      }).catch(err => {
        _self.$message({
          message: '保存失败! ' + err,
          type: 'error'
        })
        if (typeof this.formOptions === 'object') {
          this.formOptions.saveLoading = false
        }
        reject.call(_self, err)
      })
    })
  },
  // 使用delete删除数据，基本的URL为 /category/:id 这种格式
  deleteData (url) {
    let _self = this
    this.loading = true
    return new Promise((resolve, reject) => {
      request.delete(url).then(response => {
        _self.$message({
          message: '删除成功',
          type: 'success'
        })
        resolve.call(_self, response)
      }).catch(err => {
        _self.$message({
          message: '删除失败! ' + err,
          type: 'error'
        })
        reject.call(_self, err)
      })
    })
  },
  // 软删除数据，即更新delete_time为最新的时间戳
  disableData (baseUrl) {
    let _self = this
    let timeStamp = (new Date()).getTime()
    let url = baseUrl + '?&delete_time=' + timeStamp
    this.loading = true
    return new Promise((resolve, reject) => {
      request.put(url).then(response => {
        _self.$message({
          message: '软删除成功',
          type: 'success'
        })
        resolve.call(_self, response)
      }).catch(err => {
        _self.$message({
          message: '软删除失败! ' + err,
          type: 'error'
        })
        reject.call(_self, err)
      })
    })
  }
}

export default util
